<%@ page language="java" contentType="text/html;" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<!DOCTYPE html>
<html>
<head>
    <title>航班预定</title>
<jsp:include page="../inc_jqgrid.jsp"></jsp:include>
<link rel="stylesheet" type="text/css" href="${ctx}/css/skBook.css"/>
</head>
<body>
<jsp:include page="../head.jsp"></jsp:include>
	<div class="divBox" >
			<!--航班信息-->
			<div class="cHeader">
				<img src="${ctx }/image/book/green.gif"/><span>航班信息</span>
			</div>
			<div class="cContent">
				<div class="ccHeader">
					<span id="itineraryName"></span>    <span id="periodDesc"></span>
				</div>
				<table class="tableInf" border="1" id="tbl_flights">
					<thead>
						<tr>
							<td style="width:51px">序号</td>
							<td style="width:105px">航班号</td>
							<td style="width:105px">舱位</td>
							<td style="width:584px">行程</td>
							<td style="width:103px">起飞日期</td>
							<td style="width:103px">出发时刻</td>
							<td style="width:103px">到达时刻</td>
							<td style="width:103px">单价含税（CNY/张）</td>
						</tr>
					</thead>
				</table>
				<!--旅客信息-->
				<ul class="cHeader passengerHeader">
					<li class="left"><img src="${ctx }/image/book/green.gif"/><span>旅客信息</span></li>
					<li class="right">
                        <button class="blueBtn left" onclick="importFun();">导入旅客</button>
                    <button class="blueBtn left" onclick="addFun();">添加旅客</button>&nbsp;
                    </li>
				</ul>
				<div class="passengerTab" >
                        <table id="jqGrid"></table>
				</div> 
				<!--操作-->
				<div class="priceBox">
					<p class="price">采购数量：<span id="adultCount">0</span>张&nbsp;&nbsp;&nbsp;支付金额<span class="font_money">￥&nbsp;<span id="totalAR" class="font_money">0.00</span></span></p>
					<p class="timeLimit">支付时限：<span>审核通过后24小时&nbsp;</span>最晚出票时间:<span>起飞前两天</span></p>
					<p class="operation">
						<button class="blueBtn yellow" onclick="confirmBooking(this);">支付并下单</button>
					</p>
				</div>
			</div>
		</div>


<script type="text/javascript">
var data = "";
var selectInd = "";
function confirmBooking(theBtn){
    layer.load();
	var jBtn = $(theBtn);
	jBtn.attr("disabled",true).css("background-color","#808080");
    var records = $("#jqGrid").jqGrid('getGridParam','records');
	if(records==0){
		enableSubmit(jBtn);
        layer.alert("请先填写旅客信息");
		return false;
	};
    var ids = $("#jqGrid").jqGrid('getDataIDs');
    var rows = [];
    for(var i=0;i<ids.length;i++){
        var id = ids[i];
        var row= $("#jqGrid").jqGrid("getRowData", id);
        rows.push(row);
    }
    var orderInfo = BOOKINGPAGEVARS.bookingInfoFromSearchingPage;
	orderInfo.pltmOrderPassengerList=rows;
	delete orderInfo.pltmOrder.from;
	delete orderInfo.pltmOrder.to;
	for(var n in orderInfo.pltmOrderFlights){
		var f = orderInfo.pltmOrderFlights[n];
		delete f.cabinName;
	};
	var q = $("#adultCount").text();
	orderInfo.pltmOrder.purchQuantity = q;
	$.ajax({
		type:'post',
		url:'${ctx}/order/individOrder',
		contentType:'application/json;charset=utf-8',
		data:JSON.stringify(orderInfo),
		dataType:'json',
		success:function(data){
            layer.closeAll();
			if(data.success){
				layer.alert(data.msg,{skin:'layui-layer-lan',title: ['系统提示', 'background-color:#00B2EE; color:#fff;'],closeBtn: 0}, function(index){
					enableSubmit(jBtn);
					delete orderInfo;
					delete BOOKINGPAGEVARS.bookingInfoFromSearchingPage;
					window.location.href="${ctx}/order/manage?t="+Math.random();
				});
			}
			else{
				layer.alert(data.msg,{skin:'layui-layer-lan',title: ['系统提示', 'background-color:#00B2EE; color:#fff;'],closeBtn: 0}, function(index){
					enableSubmit(jBtn);
				});
			};
		},
		error:function(msg){
			layer.alert("请检查您的网络连接，然后重试！");
			enableSubmit(jBtn);
		}
	}); 
}

function calcTotalAR(){
	var p = $("#price").val();
	if(!isPositiveFloat(p) ){
		layer.alert("航班价格有误！");
		return;
	}
	var q = $("#adultCount").text();
	var t = parseFloat(p).toFixed(2) * parseFloat(q).toFixed(2);
	//$("#totalAR").text(parseFloat(t).toFixed(2));
	t = Math.floor(t * 100 + 0.5000001);  
    var cents = t % 100;  
    var yuan = Math.floor(t / 100).toString();  
    for (var i = 0; i < Math.floor((yuan.length-(1+i))/3); i++)  
    	yuan = yuan.substring(0,yuan.length-(4*i+3))+','+  yuan.substring(yuan.length-(4*i+3));  
	$("#totalAR").text(yuan + '.' + (cents<10?"0":"") + cents);
}

function isPositiveInt(n) {	return /^[1-9][0-9]*$/.test(n);}
function isPositiveFloat(n){return /^[1-9][0-9]*(.[0-9]+)?$/.test(n);}

function enableSubmit(jButton){
	jButton.attr("disabled",false).css("background-color","#f9a61a");
    layer.closeAll();
}
function initPage(b){
	$("#itineraryName").text(b.pltmOrder.from+"-"+b.pltmOrder.to);
	if(b.pltmOrder.routingType=='ROUND'){
		$("#periodDesc").text("往返间隔天数："+b.pltmOrder.travelDays);
	}
	if(b.pltmOrder.routingType=='ROUND'){
		for(var n in b.pltmOrderFlights){
			var f = b.pltmOrderFlights[n];
			var temp = "";
			if(n==0){
				temp = "<td rowspan='2'><input type='text' id='price' style='border:none;text-align:center;' readonly='readonly' value='"+CommonConverter.formatMoney(b.pltmOrder.unitPrice)+"'/></td>";
			}
			$("#tbl_flights").append("<tr class='table_body'>"
				+"<td>"+f.flightSegment+"</td>"
				+"<td>"+f.flightNumber+"</td>"
				+"<td>"+CommonConverter.toFlightCabinTypeStr(f.cabin)+"</td>"
				+"<td>"+f.departureCity+"（"+f.departureCode+"）"+f.departureTerminal+"-"+f.arrivalCity+"（"+f.arrivalCode+"）"+f.arrivalTerminal+"</td>"
				+"<td>"+f.departureDate+"</td>"
				+"<td>"+CommonConverter.formatFlightTime(f.departureTime)+"</td>"
				+"<td>"+CommonConverter.formatFlightTime(f.arrivalTime) + (f.intervalDay>0?("(+"+f.intervalDay+")"):"")+"</td>"
				+ temp
				+"</tr>");
		} 
	}else{
		var f = b.pltmOrderFlights[0];
		$("#tbl_flights").append("<tr class='table_body'>"
			+"<td>"+f.flightSegment+"</td>"
			+"<td>"+f.flightNumber+"</td>"
			+"<td>"+CommonConverter.toFlightCabinTypeStr(f.cabin)+"</td>"
			+"<td>"+f.departureCity+"（"+f.departureCode+"）"+f.departureTerminal+"-"+f.arrivalCity+"（"+f.arrivalCode+"）"+f.arrivalTerminal+"</td>"
			+"<td>"+f.departureDate+"</td>"
			+"<td>"+CommonConverter.formatFlightTime(f.departureTime)+"</td>"
			+"<td>"+CommonConverter.formatFlightTime(f.arrivalTime) + (f.intervalDay>0?("(+"+f.intervalDay+")"):"")+"</td>"
			+"<td rowspan='2'><input type='text' id='price' style='border:none;text-align:center;' readonly='readonly' value='"+CommonConverter.formatMoney(b.pltmOrder.unitPrice)+"'/></td>"
			+"</tr>");
	}
};
//添加旅客信息
function addFun(){
	layer.open({
		type: 2,
        title: ['添加乘客信息','background-color:#00B2EE; color:#fff;'],
		shadeClose: false,
		shade: 0.3,
        fix: false,
		closeBtn: 1, //不显示关闭按钮
		yes: function(index, layero) {
			layer.close(index);
		},
		area: ['600px', '550px'],
		content: ['${ctx}/order/toPassengerAddTemp', 'no'], //iframe的url，no代表不显示滚动条
		end:function(){
		}
	});
};
//添加旅客信息
function importFun(){
    layer.open({
        type: 2,
        title: ['乘客导入','background-color:#00B2EE; color:#fff;'],
        shadeClose: false,
        shade: 0.3,
        fix: false,
        closeBtn: 1, //不显示关闭按钮
        yes: function(index, layero) {
            layer.close(index);
        },
        area: ['600px', '550px'],
        content: ['${ctx}/np/orderPassengerImp', 'no'], //iframe的url，no代表不显示滚动条
        end:function(){
        }
    });
};
var ind = 0;
function setData(data){
	if(selectInd != ""){
        jQuery("#jqGrid").jqGrid('delRowData',selectInd);
	}
	data.id=ind;
    jQuery("#jqGrid").jqGrid("addRowData", ind, data);
    var records = $("#jqGrid").jqGrid('getGridParam','records');
	$("#adultCount").text(records);
	calcTotalAR();
    ind++;
};
function impData(data){
    if(selectInd != ""){
        jQuery("#jqGrid").jqGrid('delRowData',selectInd);
    }
    $.each(data, function (n, item) {
        item.id=ind;
        jQuery("#jqGrid").jqGrid("addRowData", ind, item);
        ind++;
    });
    var records = $("#jqGrid").jqGrid('getGridParam','records');
    $("#adultCount").text(records);
    calcTotalAR();
};
function delFun(index){
    jQuery("#jqGrid").jqGrid('delRowData',index);
    var records = $("#jqGrid").jqGrid('getGridParam','records');
    $("#adultCount").text(records);
	calcTotalAR();
};
//编辑旅客信息
function editFun(index){
	selectInd = index;
	var json = $('#jqGrid').jqGrid('getRowData',index);
	data = JSON.stringify(json);
	layer.open({
		type: 2,
        title: ['修改乘客信息','background-color:#00B2EE; color:#fff;'],
		shadeClose: false,
		shade: 0.3,
        fix: false,
		closeBtn: 1, //不显示关闭按钮
		yes: function(index, layero) {
			layer.close(index);
		},
        area: ['600px', '550px'],
		content: ['${ctx}/order/toPassengerAddTemp', 'no'], //iframe的url，no代表不显示滚动条
		end:function(){
			data = "";
			selectInd = "";
		}
	});
};
 
var BOOKINGPAGEVARS={"bookingInfoFromSearchingPage":{}};
$(function(){
	BOOKINGPAGEVARS.bookingInfoFromSearchingPage = JSON.parse('${bookingInfoJsonString}');
	initPage(BOOKINGPAGEVARS.bookingInfoFromSearchingPage);
	//加载旅客信息
    $("#jqGrid").jqGrid({
        url:'${ctx}',
        dataType:'local',
        styleUI:'Bootstrap',
        shrinkToFit: false,//按比例初始化列宽度
        viewrecords: true,//是否要显示总记录数
        rownumbers: true,//显示行顺序号
        rownumWidth: 35,//顺序号宽度
        //multiselect: true,//定义是否可以多选
       // multiboxonly: true,//为ture时只有选择checkbox才会起作用
        height : "100%", //"100%"
        rowNum: 500,//每页行数
        rowList : [ 500 ],//调整表格显示的记录数
        width: 1300,
        caption: "",//标题
        colModel: [
            { label: 'Id', name: 'id', key: true, width: 75,hidden:true  },
            { label: '票号', name: 'ticketNumber', key: true, width: 100,hidden:true },
            { label: '', name: 'lastName_en', key: true, width: 75,hidden:true },
            { label: '', name: 'firstName_en', key: true, width: 75,hidden:true },
            { label: '', name: 'lastName_cn', key: true, width: 75,hidden:true },
            { label: '', name: 'firstName_cn', key: true, width: 75,hidden:true },
            { label: '', name: 'sex', key: true, width: 75,hidden:true },
            { label: '', name: 'passageType', key: true, width: 75,hidden:true },
            { label: '', name: 'docType', key: true, width: 75,hidden:true },
            { label: '旅客姓名', name: 'Customer1', width: 70,
                formatter : function(value,ops,row){
                var lastNameEn=row.lastName_en;
                var firstNameEn=row.firstName_en;
                return "<span>"+lastNameEn+"</span>"+"<span>"+firstNameEn+"</span>"
            } },
            { label: '中文姓名', name: 'Customer2', width: 70,
                formatter : function(value,ops,row){
                    var lastNamecn=row.lastName_cn;
                    var firstNamecn=row.firstName_cn;
                    return "<span>"+lastNamecn+"</span>"+"<span>"+firstNamecn+"</span>"
                }},
            { label: '性别', name: 'sex1', width: 40,
                formatter : function(value,ops,row){
                    if(row.sex ==2){
                        return "女";
                    }else if(row.sex==1){
                        return "男";
                    };
                }},
            { label:'旅客类型', name: 'passageType1', width: 70,
                formatter : function(value,ops,row){
                    if(row.passageType ==0){
                        return "婴儿";
                    }else if(row.passageType==1){
                        return "成人";
                    }else if(row.passageType == 2){
                        return "儿童";
                    };
                }},
            { label:'证件类别', name: 'docType1', width: 70,
                formatter : function(value,ops,row){
                    if(row.docType==1){
                        return "身份证 ";
                    }else if(row.docType == 2){
                        return "护照";
                    };
                }},
            { label:'证件号', name: 'docId', width: 100 },
            { label:'证件有效期', name: 'docExpireDate', width: 80 },
            { label:'出生日期', name: 'birthDate', width: 80 },
            { label:'手机号', name: 'mobile', width: 100 },
            { label:'国籍', name: 'nationality', width: 80 },
            { label:'签发国家', name: 'issueCountry', width: 80 },
            { label:'酒店', name: 'grogshop', width: 100 },
            { label:'联运', name: 'throughTraffic', width: 100 },
            { label:'备注', name: 'remark', width: 100 },
            { label:'操作', name: 'act', width: 70,
                formatter : function(value,ops, row) {
                    var str = '<a href="javascript:void(0)" onclick="editFun(\''+row.id+'\');" >修改</a>&nbsp;<a href="javascript:void(0)" onclick="delFun(\''+row.id+'\');" >删除</a>';
                    return str;
                }}
        ]
	});
});
</script>
<jsp:include page="../footer.jsp"></jsp:include>
</body>
</html>